package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.GlobalConstant;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.IEmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * 员工控制器
 *
 * @author Dui
 * @since 2022/10/31 19:53
 */
@Slf4j
@RestController
@RequestMapping("/employee")
@RestControllerAdvice
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employeepram, HttpServletRequest request){
        //前端传入的所有参数都是不可靠的
        //用户名和密码的参数校验
        //至少用户名和密码不应该是空的
        //参数校验
        if (StringUtils.isBlank(employeepram.getUsername()) ||
                StringUtils.isBlank(employeepram.getPassword())){
            return R.error(GlobalConstant.FAILED);
        }
        log.info("前后端联通 ===>{}",employeepram.toString());
        //1.根据页面提交的用户名username查询数据库中员工数据信息
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employeepram.getUsername());
        //这个是数据库中的数据
        Employee employee = this.employeeService.getOne(queryWrapper);
        //2.如果没有查询到, 则返回登录失败结果
        if(employee == null){
            return R.error("登录失败");
        }
        //3.将页面提交的密码password进行md5加密处理, 得到加密后的字符串
        String m5Password = DigestUtils.md5DigestAsHex(employeepram.getPassword().getBytes());

        //4.密码比对，如果不一致, 则返回登录失败结果
        if(!(employee.getPassword().equals(m5Password))){
            //如果密码不一致
            return R.error("登录失败");
        }
        //5.查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        //员工状态 1正常，0禁用
        if (employee.getStatus()==0){
            return R.error("员工被禁用");
        }
        //6.登录成功，将员工id存入Session, 并返回登录成功结果
        request.getSession().setAttribute("employee",employee.getId());
        return R.success(employee);
    }
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理session
        request.getSession().removeAttribute("employee");
        return R.success("登出成功");
    }

    /**
     * 新增员工
     * @param employeeparam
     * @param request
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employeeparam,HttpServletRequest request){
        //前后端联通
        log.info("employeeparam ===>{}",employeeparam.toString());
        //默认密码
        String password = "123456";
        //保存到数据库中需要加密
        //加密后的密码
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        //设置默认密码
        employeeparam.setPassword(md5Password);
        //再取时间的时候，如果确定要在多个字段里写同一个时间
//        //要记得先把书记兼定义出来，然后在赋值
//        LocalDateTime now = LocalDateTime.now();
//        //创建时间 = LocalTime.now()
//        employeeparam.setCreateTime(now);
//        //更新时间 = LocalTime.now()
//        employeeparam.setUpdateTime(now);
//        //当前用户ID
//        Long currentUserId = (Long) request.getSession().getAttribute(GlobalConstant.EMPLOYEE_ID);
//        //创建人ID
//        employeeparam.setCreateUser(currentUserId);
//        //修改人ID
//        employeeparam.setUpdateUser(currentUserId);
        //保存
        this.employeeService.save(employeeparam);
        return R.success(GlobalConstant.SUCCESS);
    }
    /**
     * 分页查询
     */
    @GetMapping("/page")
    public R<Page<Employee>> getPage(Integer page,Integer pageSize,String name){
        log.info("前后端连通");
        //mybatisPlus  完成分页查询
        //mp需要分页插件
        Page<Employee> queryPage = new Page<>();
        //当前页
        queryPage.setCurrent(page);
        //当前页要显示多少行
        queryPage.setSize(pageSize);
        //查询条件拼接
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //第一个参数是布尔值，true拼接，false不拼接
        queryWrapper.like(StringUtils.isNotBlank(name),Employee::getName,name);
        Page<Employee> employeePage = this.employeeService.page(queryPage, queryWrapper);
        return R.success(employeePage);
    }
    /**
     * 更新员工信息
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employeeParam,HttpServletRequest request){
        log.info("前后端连通");
        //更新人，要在session中
        Long currentUserId = (Long) request.getSession().getAttribute(GlobalConstant.EMPLOYEE_ID);
        //更新人
        employeeParam.setUpdateUser(currentUserId);
        // 更新时间
        // 1.
        // js无法处理超过16位的数字
        // 现阶段使用雪花算法的情况又比较多
        // 要考虑是不是因为js数字的问题.
        // 2.
        // 可以通过消息转换器,来改变我们的返回值的类型
        // 我们如果要是能把返回值的id从数字类型改为字符串
        // 先确认前端传入的数据是否是正确的,指的id是否是正确的.
        employeeParam.setUpdateTime(LocalDateTime.now());
        this.employeeService.updateById(employeeParam);
        return R.success(GlobalConstant.SUCCESS);
    }
    //1.请求路径
    //2.请求方式
    //3.请求参数
    //4.返回值
    // 路径传参

    /**
     *编辑
     */
    @GetMapping("{id}")
    public R<Employee> getById(@PathVariable Long id){
        if (id <= 0){
            return R.error(GlobalConstant.FAILED);
        }
        Employee employee = this.employeeService.getById(id);
        if (employee == null){
            return R.error(GlobalConstant.FAILED);
        }
        return R.success(employee);
    }
}